package com.woniu108.order.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.order.model.dto.OrderServiceDto;
import com.woniu108.order.model.form.OrderServiceAddForm;
import com.woniu108.order.model.form.OrderServicePayForm;
import com.woniu108.order.model.form.OrderServiceQueryConditionForm;
import com.woniu108.order.model.param.OrderServiceAddParam;
import com.woniu108.order.model.param.OrderServiceQueryConditionParam;
import com.woniu108.order.model.param.OrderServiceQueryConditionToStoreAdminParam;
import com.woniu108.order.service.OrderServiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 服务订单 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/orderService")
@Api(tags = "服务订单接口")
public class OrderServiceController {
    @Resource
    private OrderServiceService orderServiceService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * token获取用户id
     * @param token userId
     * @return userId
     */
    public String getUserIdByToken(String token){
        String refreshToken = redisUtil.getString(token);
//        System.out.println("===userId:"+Integer.parseInt(JWTUtil.parseUserToken(refreshToken).get("userId").toString()));
        return JWTUtil.parseUserToken(refreshToken).get("userId").toString();
    }

    /**
     * token获取门店管理员id
     * @param token adminId
     * @return adminId
     */
    public String getStoreAdminIdByToken(String token){
        String refreshToken = redisUtil.getString(token);
        return JWTUtil.parseStoreAdminToken(refreshToken).get("storeAdminId").toString();
    }

    /**
     * 取出登录中的门店管理员id
     * @param token
     * @return storeAdminId
     */
    public String getStoreAdminId(String token){
        String refreshToken=redisUtil.getString(token);
        String storeAdminId=JWTUtil.parseStoreAdminToken(refreshToken).get("storeAdminId").toString();
        return storeAdminId;
    }

    /**
     * 按条件查询服务订单（管理员）
     * @param form 查询订单参数
     * @return 分页后的服务订单集合
     */
    @PostMapping("/queryOrderServicesByCondition.api")
    @ApiOperation("按条件查询服务订单（管理员）")
    public Result<Page<OrderServiceDto>> queryOrderServicesByCondition(@RequestBody OrderServiceQueryConditionForm form){
        OrderServiceQueryConditionParam param = BeanUtil.toBean(form, OrderServiceQueryConditionParam.class);
        Page<OrderServiceDto> orderServiceDtos=orderServiceService.selectOrderServicesByCondition(param);
        return Result.newPageInstance(OrderServiceDto.class).setData(orderServiceDtos);
    }

    /**
     * 按条件查询服务订单（门店）
     * @param form 查询服务订单条件
     * @param token adminId
     * @return 分页后的服务订单集合
     */
    @PostMapping("/queryOrderServicesByConditionToStore.st")
    @ApiOperation("按条件查询服务订单（门店）")
    public Result<Page<OrderServiceDto>> queryOrderServicesByConditionToStore(@RequestBody OrderServiceQueryConditionForm form, @RequestHeader String token){
        String storeAdminId = getStoreAdminIdByToken(token);

        OrderServiceQueryConditionToStoreAdminParam param= BeanUtil.toBean(form, OrderServiceQueryConditionToStoreAdminParam.class);
        param.setStoreAdminId(storeAdminId);
        Page<OrderServiceDto> orderServiceDtos=orderServiceService.selectOrderServicesByConditionToStore(param);
        return Result.newPageInstance(OrderServiceDto.class).setData(orderServiceDtos);
    }

    /**
     * 按条件查询服务订单（用户）
     * @param form "查询订单参数"
     * @param token userId
     * @return 分页后服务订单集合
     */
    @PostMapping("/queryOrderServicesByConditionToUser")
    @ApiOperation("按条件查询服务订单（用户）")
    public Result<Page<OrderServiceDto>> queryOrderServicesByConditionToUser(@RequestBody OrderServiceQueryConditionForm form, @RequestHeader String token){
        String userId = getUserIdByToken(token);

        OrderServiceQueryConditionParam param = BeanUtil.toBean(form, OrderServiceQueryConditionParam.class);
        param.setUserId(userId);
        Page<OrderServiceDto> orderServiceDtos=orderServiceService.selectOrderServicesByConditionToUser(param);
        return Result.newPageInstance(OrderServiceDto.class).setData(orderServiceDtos);
    }

    /**
     * 按订单编号精确查询服务订单
     * @param orderServiceNum 服务订单编号
     * @return 订单服务信息dto
     */
    @GetMapping("/queryOrderServiceByOrderServiceNum/{orderServiceNum}.c")
    @ApiOperation("按订单编号精确查询服务订单")
    public Result<OrderServiceDto> queryOrderServiceByOrderServiceNum(@PathVariable("orderServiceNum") @ApiParam("服务订单编号") String orderServiceNum){
        OrderServiceDto  orderServiceDto=orderServiceService.selectOrderServiceByOrderServiceNum(orderServiceNum);
        return Result.getResult(OrderServiceDto.class).setData(orderServiceDto).setMsg("按订单编号查询成功");
    }

    /**
     * 根据服务订单编号修改评分状态
     * @param orderServiceNum 服务订单编号
     * @return Boolean值
     */
    @GetMapping("/modifyOrderServiceReviewStateByOrderServiceNum/{orderServiceNum}.c")
    @ApiOperation("根据服务订单编号修改评分状态")
    public Result<Boolean> modifyOrderServiceReviewStateByOrderServiceNum(@PathVariable("orderServiceNum") @ApiParam("服务订单编号")String orderServiceNum){
        Boolean aBoolean=orderServiceService.updateOrderServiceReviewStateByOrderServiceNum(orderServiceNum);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("修改状态成功");
    }


    /**
     * 用户取消订单，未支付时
     * @param orderServiceNum 服务订单编号
     * @param token userId
     * @return Boolean值
     */
    @GetMapping("/cancelServiceOrder/{orderServiceNum}")
    @ApiOperation("用户取消订单，未支付时")
    public Result<Boolean> cancelOrder(@PathVariable("orderServiceNum") @ApiParam("服务订单") String orderServiceNum,@RequestHeader String token){
        String userId = getUserIdByToken(token);
        Boolean aBoolean=orderServiceService.cancelOrder(orderServiceNum,userId);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("操作成功，订单已取消");
    }

    /**
     * 删除订单
     * @param orderServiceNum 服务订单编号
     * @param token userId
     * @return boolean值
     */
    @GetMapping("/deleteServiceOrder/{orderServiceNum}.c")
    @ApiOperation("删除订单")
    public Result<Boolean> deleteOrder(@PathVariable("orderServiceNum")@ApiParam("服务订单编号")String orderServiceNum,@RequestHeader String token){
        String userId = getUserIdByToken(token);
        Boolean aBoolean=orderServiceService.deleteOrder(orderServiceNum,userId);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("删除订单成功");
    }

    /**
     * 服务下单（门店） 还未设置消息队列
     * @param form 用户id，下单时间，下单的服务id及其对应使用商品id集合
     * @param token storeAdminId
     * @return 判断
     */
    @PostMapping("/orderService.st")
    @ApiOperation("服务下单（门店）")
    public Result<Boolean> orderService(@RequestBody OrderServiceAddForm form,@RequestHeader String token){
        String storeAdminId = getStoreAdminId(token);

        OrderServiceAddParam param = BeanUtil.toBean(form, OrderServiceAddParam.class);
        param.setStoreAdminId(storeAdminId);

        Boolean aBoolean=orderServiceService.orderService(param,token);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("下单成功");
    }

    /**
     * 普通支付订单(用户)
     * @param orderServiceNum 服务订单编号
     * @param token userId
     * @return 支付表单
     * @throws Exception
     */
    @GetMapping("/payByCommon/{orderServiceNum}")
    @ApiOperation("普通支付订单(用户)")
    public Result<String> pay(@PathVariable("orderServiceNum") @ApiParam("服务订单编号")String orderServiceNum, @RequestHeader String token) throws Exception {
        String userId = getUserIdByToken(token);
        String pay=orderServiceService.payByCommon(orderServiceNum,userId,token);
        return Result.getResult(String.class).setData(pay).setMsg("发起支付成功");
    }

    @GetMapping("/payByVip/{orderServiceNum}")
    @ApiOperation("vip支付订单(vip用户)")
    public Result<String> payByVip(@PathVariable("orderServiceNum")@ApiParam("服务订单编号")String orderServiceNum, @RequestHeader String token) throws Exception {
        String userId = getUserIdByToken(token);
        String pay=orderServiceService.payByVip(orderServiceNum,userId);
        return Result.getResult(String.class).setData(pay).setMsg("vip发起支付成功");
    }

    /**
     * 支付回调
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/payNotify")
    @ApiOperation("支付回调")
    public String payNotify(HttpServletRequest request) throws Exception{
        Map<String,String> params = new HashMap<String,String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        orderServiceService.payNotify(params);
        return "SUCCESS";
    }

    /**
     * 修改服务订单状态,验证流程是否走完
     * @param orderNum 订单编号
     * @return 布尔值
     */
    @GetMapping("/updateOrderServiceStateByOrderNum/{orderNum}.c")
    @ApiOperation("修改服务订单状态")
    public Result<Boolean> updateOrderServiceStateByOrderNum(@PathVariable("orderNum")@ApiParam("服务订单编号")String orderNum){
        Boolean aBoolean=orderServiceService.updateOrderServiceStateByOrderNum(orderNum);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("修改状态成功");
    }

    @GetMapping("/finishOrder/{orderNum}.c")
    @ApiOperation("完成订单")
    public Result<String> finishOrder(@ApiParam("订单编号")@PathVariable("orderNum")String orderNum){
        String orderServiceNum=orderServiceService.finishOrderState(orderNum);
        return Result.getResult(String.class).setData(orderServiceNum).setMsg("订单已完成");
    }
}

